<template>
  <div class="containers">
    <div class="container">
      <div class="form-box" style="width: 100%;padding: 20px;">
        <el-form ref="form" :model="form" label-width="140px" :rules="rules">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入商品名称" style="max-width: 265px;"></el-input>
          </el-form-item>

          <el-form-item label="商品分区" prop="name">
            <el-select v-model="form.partition_id" @change="setfirst" placeholder="请选择商品分区" size="small" class="mr10">
              <el-option v-for="(item, index) in navigation_list" :key="item.ID" :label="item.name"
                :value="item.ID"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="一级分类" prop="name">
            <el-select v-model="form.class_first_id" @change="setfirst" placeholder="请选择一级分类" size="small" class="mr10">
              <el-option v-for="(item, index) in firstlist" :key="item.ID" :label="item.name"
                :value="item.ID"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类">
            <el-select v-model="form.class_second_id" placeholder="请选择二级分类" size="small" class="mr10"
              @change="setsecond">
              <el-option v-for="(item, index) in secondlist" :key="item.ID" :label="item.name"
                :value="item.ID"></el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="三级分类">-->
<!--            <el-select v-model="form.class_third_id" placeholder="请选择三级分类" size="small" class="mr10">-->
<!--              <el-option v-for="(item, index) in thirdlist" :key="item.ID" :label="item.name"-->
<!--                :value="item.ID"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="商品分类" prop="name">
            <el-select v-model="form.business_class_id" placeholder="请选择商品分类" size="small" class="mr10">
              <el-option v-for="(item, index) in BusinessClassList" :key="item.ID" :label="item.name"
                :value="item.ID"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="首购区">
					<el-select v-model="form.is_single"  placeholder="请选择首购区" size="small" class="mr10">
						<el-option v-for="(item, index) in optionss" :key="item.ID" :label="item.name"
							:value="item.ID"></el-option>
					</el-select>
				</el-form-item> -->
          <el-form-item label="商品简介" prop="name">
            <el-input type="textarea" maxlength="42" show-word-limit rows="3" v-model="form.title"
              placeholder="请输入商品简介"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="name">
            <el-input v-model="form.price" placeholder="请输入商品价格" onkeyup="value=value.replace(/[^\d.]/g,'')"
              style="max-width: 265px;"></el-input>
          </el-form-item>
          <!-- <el-form-item label="pv值" prop="name">
            <el-input v-model="form.pv" type="Number" placeholder="请输入pv值" onkeyup="value=value.replace(/[^\d.]/g,'')"
              style="max-width: 265px;"></el-input>
          </el-form-item> -->


<!--          <el-form-item label="市场价格" prop="name">-->
<!--            <el-input v-model="form.market" onkeyup="value=value.replace(/[^\d.]/g,'')" style="max-width: 265px;"-->
<!--              placeholder="请输入市场价格"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="ZKFC" prop="name">-->
<!--            <el-input v-model="form.coupon" onkeyup="value=value.replace(/[^\d.]/g,'')" style="max-width: 265px;"-->
<!--              placeholder="请输入ZKFC"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="商品库存" prop="name">
            <el-input v-model="form.stock" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 265px;"
              placeholder="请输入商品库存"></el-input>
          </el-form-item>
          <el-form-item label="商品虚拟销量" prop="name">
            <el-input v-model="form.virtually_sales" onkeyup="value=value.replace(/[^\d]/g,'')"
              style="max-width: 265px;" placeholder="请输入商品虚拟销量"></el-input>
          </el-form-item>
          <el-form-item label="商品排序" prop="name">
            <el-input v-model="form.sort" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 265px;"
              placeholder="请输入商品排序"></el-input>
          </el-form-item>
<!--          <el-form-item label="会员让利（⩽30）" prop="discount">-->
<!--            <el-input v-model="form.discount" max="30" onkeyup="value=value.replace(/[^\d.]/g,'')" style="max-width: 265px;"-->
<!--              placeholder="请输入让利"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="平台让利（⩽80）" prop="platform_discount">-->
<!--            <el-input v-model="form.platform_discount" max="80" onkeyup="value=value.replace(/[^\d.]/g,'')" style="max-width: 265px;"-->
<!--              placeholder="请输入让利"></el-input>-->
<!--          </el-form-item>-->

<!--          <el-form-item label="供货价" prop="supply">-->
<!--            <el-input v-model="form.supply" onkeyup="value=value.replace(/[^\d.]/g,'')" style="max-width: 265px;"-->
<!--              placeholder="请输入供货价"></el-input>-->
<!--          </el-form-item>-->

          <!-- <el-form-item label="赠送购物券" prop="name">
            <el-input v-model="form.integral_send" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 265px;"
              placeholder="请输入赠送购物券"></el-input>
          </el-form-item>
          <el-form-item label="赠送nft" prop="name">
            <el-input v-model="form.nft_card_num" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 265px;"
              placeholder="请输入赠送nft"></el-input>
          </el-form-item>
          <el-form-item label="赠送消费金" prop="name">
            <el-input v-model="form.balance_send" onkeyup="value=value.replace(/[^\d]/g,'')" style="max-width: 265px;"
              placeholder="请输入赠送消费金"></el-input>
          </el-form-item> -->

         <el-form-item label="是否可用余额">
           <el-switch :active-value="1" :inactive-value="0" v-model="form.is_cash"></el-switch>
         </el-form-item>
          <!-- <el-form-item label="是否展示pv">
            <el-switch :active-value="1" :inactive-value="0" v-model="form.is_pv"></el-switch>
          </el-form-item> -->
          <!-- <el-form-item label="首页展示">
            <el-switch :active-value="1" :inactive-value="0" v-model="form.is_index"></el-switch>
          </el-form-item>
          <el-form-item label="推荐展示">
            <el-switch :active-value="1" :inactive-value="0" v-model="form.is_extension"></el-switch>
          </el-form-item>
          <el-form-item label="热卖展示">
            <el-switch :active-value="1" :inactive-value="0" v-model="form.is_hot"></el-switch>
          </el-form-item> -->
          <el-form-item label="展示图片" prop="name">
            <div style="color:red;">建议比例:400/400</div>
            <el-upload class="avatar-uploader" :action="upload + '/'" :show-file-list="false" :data="upimg"
              :on-success="handleAvatarSuccess" :before-upload="beforeupload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="展示视频">
            <div style="color:red;">比例:750/500</div>
            <el-upload :action="upload + '/'" :show-file-list="false" :data="upimg" :on-success="handleAvatarSuccesss"
              :before-upload="beforeuploads">
              <video v-if="videoUrl" :src="videoUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="轮播图" prop="name">
            <div style="color:red;">比例:750/500</div>
            <el-upload :action="upload + '/'" list-type="picture-card" :on-preview="handlePictureCardPreview"
              :before-upload="beforeAvatarUpload" :on-success="someSuccess" :data="upimg" :limit="4"
              :file-list="filelist" :on-remove="handleRemove">
              <i class="el-icon-plus" style="line-height: 90px;text-align: center;"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
            <div>最多上传4张</div>
          </el-form-item>
          <el-form-item label="资质">

            <el-upload class="avatar-uploader" :action="upload + '/'" :show-file-list="false" :data="upimg"
              :on-success="handleAvatarSuccessmaterial" :before-upload="beforeuploadmaterial">
              <img v-if="imageUrlmaterial" :src="imageUrlmaterial" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品规格" prop="name">
            <el-collapse v-model="activeName">
              <el-collapse-item title="规格管理(点击展开更多设置)" name="2">
                <div>
                  <el-button plain @click="addattrubut">添加规格</el-button>
                  <el-button plain @click="autoprice">一键填写价格</el-button>
                  <el-button plain @click="autostock">一键添加库存</el-button>
                  <!-- <el-button plain @click="addnewattr">新增新规格</el-button> -->
                </div>
                <div style="margin-top: 10px;">
                  <el-table :data="attrubutetable" class="table" ref="multipleTable"
                    header-cell-class-name="table-header">
                    <el-table-column prop="type_name" label="规格名称" header-align="center" width="150" align="center">
                      <template slot-scope="scope">
                        <el-select v-model="scope.row.type_name" v-if="attrlist.length > 0" placeholder="请选择规格"
                          @change="shooseattr(scope.row)">
                          <el-option v-for="(i, index) in attrlist" :key="index" :label="i.type_name"
                            :value="i.type_name"></el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column label="规格值" header-align="center">
                      <template slot-scope="scope" v-if="scope.row.index >= 0 && attrlist.length > 0">
                        <el-button plain :class="scope.row.attrindexlist[rowindex] == 1 ? 'activeattr' : ''"
                          @click="clickattr(scope.row, rowindex)"
                          v-for="(i, rowindex) in attrlist[attrlist.findIndex(is => is.type_name == scope.row.type_name)].type_attr"
                          :key="rowindex">
                          {{ i.val }} <!--    {{ attrlist.findIndex(is=>is.type_name==scope.row.type_name) }} -->
                        </el-button>

                      </template>
                    </el-table-column>
                    <el-table-column label="操作" header-align="center" width="80">
                      <template slot-scope="scope">
                        <el-button plain @click="deleteattr(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <!-- 属性价格表 -->
                <div style="margin-top: 10px;">
                  <el-table :data="attrpricetable" v-if="attrpricetable.length > 0 && attrubutetable.length > 0"
                    class="table" ref="multipleTable" header-cell-class-name="table-header">
                    <el-table-column :prop="i.type_name" :label="i.type_name" v-for="(i, inde) in attrubutetable"
                      :key="inde" header-align="center" min-width="80" align="center">
                      <template slot-scope="scope" v-if="scope.row.attr[inde]">
                        {{ scope.row.attr[inde].val }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="type_name" label="价格" header-align="center" min-width="80" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.price" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                      </template>
                    </el-table-column>
                    <!-- <el-table-column prop="type_name" label="供货价" header-align="center" min-width="80" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.supply" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                      </template>
                    </el-table-column> -->
                    <!-- <el-table-column prop="type_name" label="PV值" header-align="center" min-width="80" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.pv" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>
                      </template>
                    </el-table-column> -->
<!--                    <el-table-column prop="type_name" label="ZKFC" header-align="center" min-width="80" align="center">-->
<!--                      <template slot-scope="scope">-->
<!--                        <el-input v-model="scope.row.coupon" onkeyup="value=value.replace(/[^\d.]/g,'')"></el-input>-->
<!--                      </template>-->
<!--                    </el-table-column>-->
                    <el-table-column prop="type_name" label="库存" header-align="center" min-width="80" align="center">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.stock" onkeyup="value=value.replace(/[^\d]/g,'')"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="type_name" label="展示图(可选)" header-align="center" min-width="150"
                      align="center">
                      <template slot-scope="scope">
                        <el-upload class="upload-demo" action="http://upload.qiniup.com/" :show-file-list="false"
                          :data="upimg" :objectBind="scope.$index" :before-upload="beforeAvatarUpload"
                          :on-success="handSuccessmore">
                          <img @click="sss(scope.$index)" v-if="form.img || scope.row.img"
                            :src="scope.row.img ? scope.row.img : form.img" style="width: 50px;height: 50px;" />
                          <el-button @click="sss(scope.$index)" v-if="!form.img && !scope.row.img" size="small"
                            type="primary">点击上传</el-button>
                        </el-upload>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" header-align="center" width="80">
                      <template slot-scope="scope">
                        <el-button plain @click="deletpraci(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-collapse-item>
            </el-collapse>
          </el-form-item>
          <el-form-item label="商品详情" prop="name">
            <my-editor @getContent="getContent" :content="form.details" ref="editor"></my-editor>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">表单提交</el-button>
            <el-button @click="back"> 取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import MyEditor from '@/components/MyEditor.vue'
export default {
  name: 'addgoods',
  components: {
    MyEditor
  },
  data() {
    return {
      optionss: [{ name: '普通', ID: 0 }, { name: '百元区', ID: 1 }, { name: '千元区', ID: 2 }, { name: '万元区', ID: 3 }, { name: '兑换区', ID: 4 }], //分区类型 下拉选项
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
      },
      options: [],
      price: '',
      select: false,
      isselect: false,
      upimg: {
        token: '',
        key: new Date().valueOf()
      },
      upload: '',
      url: '',
      imageUrl: '',
      imageUrlmaterial: '',

      videoUrl: '',
      thisrow: {},
      images: [],
      showdetails: true,
      activeName: '1',
      navigation_list: [], //分区
      firstlist: [], //分类
      secondlist: [],
      filelist: [],
      thirdlist: [],
      BusinessClassList: [],//商品分类
      attrlist: [], // 属性列表
      attrubutetable: [], //'属性表'
      attrpricetable: [], //属性价格表
      dialogImageUrl: '',
      baodan: true,
      index: 0,
      dialogVisible: false,
      form: {
        is_cash: 1,
        is_single: 0,
        name: '',//商品名称
        img: '',//首页展示图
        details: '',//商品介绍
        class_first_id: '',
        class_second_id: '',
        class_third_id: '',
        business_class_id: '',
        img_list: [],
        freight: '',
        material: '',
        stock: '',
        sales: 0,
        coupon: 0,
        price: '',
        video: '',
        market: '',
        is_extension: 0,
        is_hot: 0,
        is_index: 0,
        sort: 0,
        partition_id: '',
        title: '',
        attribute_list: [],
        discount: 1,//成本价
        platform_discount:0,
        integral_send: '',//赠送购物券
        nft_card_num: '',//赠送nft的数
        balance_send: '',//赠送消费金
        virtually_sales: 0,
        is_pv: 0,
        pv: 0
      },
      addstate: true
    };
  },
  watch: {
    // 监听路由对象$route的变化
    '$route': {
      handler: function (to, from) {
        this.getData()
      },
      // 设置为深度监听
      deep: true
    }
  },
  activated() {
  },
  created() {
    this.getToken().then(res => {
      this.upimg.token = res.data.token
      this.url = res.data.url
      this.upload = res.data.upload
    },
      function () {
        console.log('请求失败处理');
      }
    )
    this.init()
    try {
      console.log(this.$route.query.id)
      if (this.$route.query.id) {
        this.getData()
        this.addstate = false
      }
    } catch {

    }
  },
  methods: {
    back() {
      this.$router.push({ path: '/commodity/goodslist' })
    },
    getData() {
      this.request('business/goodsDetails/', 'post', { id: Number(this.$route.query.id) }).then(res => {
        this.form = res.data
        this.imageUrl = res.data.img
        this.imageUrlmaterial = res.data.material
        this.form.class_first_id = res.data.class_first_id ? res.data.class_first_id : ''
        this.form.class_second_id = res.data.class_second_id ? res.data.class_second_id : ''
        this.form.class_third_id = res.data.class_third_id ? res.data.class_third_id : ''
        this.form.partition_id = res.data.partition_id ? res.data.partition_id : ''
        this.form.freight = res.data.freight ? res.data.freight : ''
        this.request('business/add_attribute/', 'get', { page: 1, size: 100 }).then(ress => {
          this.attrlist = ress.data
          //规格
          let attr = []
          let attrubutetable = []
          //处理商品规格
          res.data.attribute_list[0].attr.forEach((item, index) => {
            attrubutetable[index] = []
          })
          res.data.attribute_list.forEach((item, index) => {
            item.attr.forEach((items, indexs) => {
              let attrlist = this.attrlist.filter(i => {
                return items.attr == i.type_name
              })[0].type_attr.map(k => {
                return k.val
              })
              console.log(attrlist, '检查')
              attrubutetable[indexs] = {
                type_name: items.attr,
                index: this.attrlist.findIndex(is => is.type_name == items.attr),
                attrindexlist: attrlist,
              }
            })
            let attrs = item.attr.map(items => {
              return {
                attr: items.attr,
                val: items.val
              }
            })
            attr.push({
              attr: attrs,
              attrcash_coupon: 0,
              price: item.price,
              img: item.img,
              stock: item.stock,
              supply: item.supply,
              pv: item.pv,
              coupon: item.coupon,

            })
          })
          //处理商品规格
          let list = []
          let lists = []
          attr.forEach((item, index) => {
            list[index] = new Array
            item.attr.forEach((items, indexs) => {
              lists[indexs] = new Array
              console.log(indexs)
            })
          })
          attr.forEach((item, index) => {
            item.attr.forEach((items, indexs) => {
              list[index].push(items.val) //= [...list[indexs], items.val]
            })
          })
          for (var k = 0; k < lists.length; k++) {
            console.log(k)
            list.forEach((item, index) => {
              console.log('+++++++', index, item)
              lists[k].push(item[k]);
            })
          }

          console.log(lists)
          lists.forEach((item, index) => {
            let listbox = []
            attrubutetable[index].attrindexlist.forEach((items, indexs) => {
              listbox.push(items == item[indexs] ? 1 : 0)
            })
            attrubutetable[index].attrindexlist = listbox
          })

          this.attrubutetable = attrubutetable
          this.attrpricetable = attr
          try {
            this.filelist = eval('(' + res.data.img_list + ')').map(item => {
              return {
                name: item,
                url: item
              }
            })
            this.filelist = eval('(' + res.data.img_list + ')').map(item => {
              return {
                name: item,
                url: item
              }
            })
            this.form.img_list = eval('(' + res.data.img_list + ')')
          } catch {
            this.filelist = eval('(' + eval('(' + res.data.img_list + ')') + ')').map(item => {
              return {
                name: item,
                url: item
              }
            })
            this.filelist = eval('(' + eval('(' + res.data.img_list + ')') + ')').map(item => {
              return {
                name: item,
                url: item
              }
            })
            this.form.img_list = eval('(' + eval('(' + res.data.img_list + ')') + ')')
          }
          if (res.data.class_first_id > 0) {
            this.setfirst(false)
          }
          if (res.data.class_second_id > 0) {
            this.setsecond(false)
          }
        })


      })
    },
    //获取初始化
    init() {
      //获取运费模版
      this.request('business/freightTemplate/', 'get', { page: 1, size: 50 }).then(res => {
        this.options = res.data.data
      })
      //获取一级分类
      this.request('business/firstClass/', 'get', { page: 1, size: 100, keyword: '' }).then(res => {
        this.firstlist = res.data.data
      })
      //获取所有规格
      this.request('business/add_attribute/', 'get', { page: 1, size: 100 }).then(res => {
        this.attrlist = res.data
      })
      //获取商品分区
      this.request('business/partition/', 'get', { page: 1, size: 100 }).then(res => {
        console.log(res)
        this.navigation_list = res.data.data
      })
      //获取店铺商品分类
      this.request('business/addBusinessClass/', 'get', { page: 1, size: 100 }).then(res => {
        console.log(res)
        this.BusinessClassList = res.data.data
      })
    },
    //获取2级分类
    setfirst(isGet=true) {
      if(isGet){
        this.form.class_second_id = ''
      }
      this.request('business/secondClass/', 'get', { class_first_id: this.form.class_first_id, page: 1, size: 100, keyword: '' }).then(res => {

        if (res.data.total != 0) {
          this.secondlist = res.data.data
          this.secondlist.unshift({ name: '空', ID: 0 })

        }
      })
    },
    //获取3级分类
    setsecond(isGet=true) {
      if(isGet){
        this.form.class_third_id = ''
      }
      this.request('business/thirdClass/', 'get', { class_second_id: this.form.class_second_id, page: 1, size: 100, keyword: '' }).then(res => {
        // this.thirdlist = res.data.data
        if (res.data.total != 0) {
          this.thirdlist = res.data.data
          this.thirdlist.unshift({ name: '空', ID: 0 })
        }
      })
    },



    getContent(e) {
      console.log('editor', e)
      this.form.details = e
    },

    // 编辑商品
    sss(s) {
      this.index = s;
    },


    //一键填写价格
    autoprice() {
      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].price = this.form.price;
      }
    },


    //一键填写库存
    autostock() {
      for (var i = 0, len = this.attrpricetable.length; i < len; i++) {
        this.attrpricetable[i].stock = this.form.stock;
      }
    },
    //点击属性按钮
    clickattr(row, index) {
      row.attrindexlist[index] = row.attrindexlist[index] == 1 ? 0 : 1;
      this.attrlist[row.index].type_attr.push(1);
      this.attrlist[row.index].type_attr.pop();
      this.drawtable(); // 改变属性重新绘制绘制表格
    },
    //绘制属性价格表
    drawtable() {
      this.attrpricetable = [];
      let cpa = this.getattrprice(); //组合函数
      console.log("测试规格1", cpa)
      console.log("测试规格2", this.attrubutetable)
      for (var k = 0; k < cpa.length; k++) {
        var newarr = [];
        console.log(cpa[k])
        for (var i = 0; i < cpa[k].length; i++) {
          console.log(cpa[k][i])
          newarr.push({
            attr: this.attrubutetable[i].type_name,
            val: cpa[k][i].val
          });
        }
        this.attrpricetable.push({
          attr: newarr,
          coupon: 0,
          price: '',
          cash_coupon: 0,
          img: '',
          stock: '',
          supply: 0,
          pv: 0
        });
      }
    },
    //添加规格按钮
    addattrubut() {
      this.attrubutetable.push({
        type_name: '请选择属性',
        index: -1
      });
    },
    // 删除规格按钮
    deleteattr(row) {
      console.log(this.attrubutetable)
      this.attrubutetable = this.attrubutetable.filter(t => t.type_name != row.type_name);
      console.log(this.attrubutetable)
      this.drawtable(); // 改变属性重新绘制绘制表格
    },
    // 删除单行属性
    deletpraci(row) {
      this.attrpricetable = this.attrpricetable.filter(t => t != row);
      // console.log(this.attrpricetable)
    },
    addnewattr() {
      // this.$router.push({
      //   path: '/attributelist'
      // });
    },
    //选择属性类别
    shooseattr(row) {
      console.log(row)
      let index = 0;
      let p = this.attrubutetable.filter(t => t.type_name == row.type_name);
      if (p.length > 1) {
        row.type_name = '';
        return this.$message.error('不能选择相同属性');
      }

      for (var i = 0; i < this.attrlist.length; i++) {
        if (this.attrlist[i].type_name == row.type_name) {
          index = i;
          break;
        }
      }
      for (var i = 0; i < this.attrubutetable.length; i++) {
        if (this.attrubutetable[i].type_name == row.type_name) {
          this.attrubutetable[i].index = index;
          break;
        }
      }
      this.attrubutetable[i].attrindexlist = [];
      this.attrlist[i].type_attr.forEach(f => {
        this.attrubutetable[i].attrindexlist.push(0);
      });
    },


    handlePictureCardPreview(res, file) {
      this.dialogImageUrl = this.url + res.key;
      this.dialogVisible = true;
    },

    handleRemove(res, file) {
      console.log(res, file)
      this.filelist = file
      this.form.img_list = file.map(item => {
        return item.url
      })
    },



    async beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'video/mp4') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      // if (file.size / 1024*1024> 500 && file.type !== 'video/mp4') {
      // 	this.$message.error('上传图标大小不能超过 500k!');
      // 	return false;
      // }
      let types = file.name.split('.')//获取视频格式
      this.upimg.key = this.$name + '/home/' + new Date().valueOf() + '.' + types[types.length - 1];

    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.form.img = this.url + res.key;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeupload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('上传图标大小不能超过 1M!');
        return false;
      }
      let types = file.name.split('.')//获取图片格式
      this.upimg.key = 'template/home/' + new Date().valueOf() + '.' + types[types.length - 1];
    },
    // 上传图片
    handleAvatarSuccessmaterial(res, file) {
      this.form.material = this.url + res.key;
      this.imageUrlmaterial = URL.createObjectURL(file.raw);
    },
    beforeuploadmaterial(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG、PNG 格式!');
        return false;
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('上传图标大小不能超过 1M!');
        return false;
      }
      let types = file.name.split('.')//获取图片格式
      this.upimg.key = 'template/home/' + new Date().valueOf() + '.' + types[types.length - 1];
    },

    // 上传视频
    handleAvatarSuccesss(res, file) {
      this.form.video = this.url + res.key;
      this.videoUrl = URL.createObjectURL(file.raw);
    },
    beforeuploads(file) {
      if (file) {
        if (file.type !== 'video/mp4') {
          this.$message.error('请上传视频格式');
          return false;
        }
        if (file.size / 1024 > 10240) {
          this.$message.error('上传视频大小不能超过 10240k!');
          return false;
        }
      }
      let types = file.name.split('.')//获取视频格式
      this.upimg.key = this.$name + '/home/' + new Date().valueOf() + '.' + types[types.length - 1];
    },
    someSuccess(res, file) {
      console.log(this.url + res.key, this.form.img_list)
      this.form.img_list.push(this.url + res.key);
      this.filelist.push({
        name: res.key,
        url: this.url + res.key
      })

    },
    handSuccessmore(res, file, files) {
      this.attrpricetable[this.index].img = this.url + res.key;
      this.thisrow.img = this.url + res.key;
    },
    //表单验证
    FormValidation() {
      let data = this.form;
      this.form.attribute_list = []
      this.attrpricetable.forEach(item => {
        item.price = Number(item.price)
        item.stock = Number(item.stock)
        item.supply = Number(item.supply)
        item.pv = 1
        item.coupon = Number(item.coupon)
        if (!item.img) {
          item.img = this.form.img
        }
        this.form.attribute_list.push(item)
      })
      console.log(data)
      if (!data.name) {
        this.$message.error('请输入商品名称');
        return false;
      }
      if (!data.partition_id > 0) {
        this.$message.error('请选择商品分区');
        return false;
      }
      if (!data.class_first_id > 0) {
        this.$message.error('请选择商品一级分类');
        return false;
      }
      if (!data.business_class_id > 0) {
        this.$message.error('请选择商品分类');
        return false;
      }

      if (!data.title) {
        this.$message.error('请输入商品简介');
        return false;
      }

      if (!data.price > 0) {
        this.$message.error('请输入商品价格');
        return false;
      }
      if (!data.stock > 0) {
        this.$message.error('请输入商品库存');
        return false;
      }

      // if (!data.integral_send>0) {
      //   this.$message.error('请输入赠送购物券');
      //   return false;
      // }
      // if (!data.nft_card_num>0) {
      //   this.$message.error('请输入赠送nft');
      //   return false;
      // }
      // if (!data.balance_send>0) {
      //   this.$message.error('请输入赠送消费金');
      //   return false;
      // }
      if (!data.img) {
        this.$message.error('请上传商品展示图片');
        return false;
      }
      console.log(this.filelist)
      if (this.filelist.length == 0) {
        this.$message.error('请上传商品轮播图片');
        return false;
      }
      if (this.form.attribute_list.length == 0) {
        this.$message.error('请选择商品规格');
        return false;
      }
      if (this.form.attribute_list.filter(item => item.price > 0).length == 0) {
        this.$message.error('规格价格需大于0');
        return false;
      }
      if (!this.form.details) {
        this.$message.error('请填写商品详情');
        return false;
      }

      return true;
    },
    onSubmit() {
      if (!this.FormValidation()) return;



      let data = JSON.parse(JSON.stringify(this.form))
      data.name = this.form.name,//商品名称
        data.img = this.form.img,//首页展示图
        data.details = this.form.details,//商品介绍
        data.class_first_id = Number(this.form.class_first_id),
        data.class_second_id = this.form.class_second_id > 0 ? Number(this.form.class_second_id) : 0,
        data.class_third_id = this.form.class_third_id > 0 ? Number(this.form.class_third_id) : 0,
        data.business_class_id = this.form.business_class_id,//Number(this.form.business_class_id),
        data.img_list = JSON.stringify(this.form.img_list),
        data.stock = Number(this.form.stock),
        data.sales = Number(this.form.sales),
        data.coupon = Number(this.form.coupon),
        data.price = Number(this.form.price),
        data.video = this.form.video,
        data.market = Number(this.form.market),
        data.is_extension = Number(this.form.is_extension),
        data.is_hot = Number(this.form.is_hot),
        data.is_index = Number(this.form.is_index),
        data.sort = Number(this.form.sort),
        data.discount = Number(this.form.discount),
        data.platform_discount = Number(this.form.platform_discount),
        data.freight = Number(this.form.freight || 0),
        data.is_cash = Number(this.form.is_cash),
        data.pv = 1,
        data.integral_send = Number(this.form.integral_send)
      data.nft_card_num = Number(this.form.nft_card_num)
      data.balance_send = Number(this.form.balance_send)
      data.virtually_sales = Number(this.form.virtually_sales)
      data.partition_id = this.form.partition_id,
        data.title = this.form.title,
        data.attribute_list = this.form.attribute_list

      if (this.$route.query.id) {
        data['id'] = Number(this.$route.query.id)
        data.ID = Number(this.$route.query.id)
      }
      this.request('business/add_goods/', this.addstate ? 'post' : 'PUT', data).then(res => {
        console.log(res)

        if (res.errno == 0) {
          this.$message.success(res.errmsg);
          setTimeout(f => {
            this.$router.push({ path: '/commodity/goodslist' })
          }, 500);
        } else {
          this.$message.error(res.errmsg);
        }
      })

    },

    // 工具函数
    doCombination(arr) {
      //排列组合算法
      var count = arr.length - 1;
      var tmp = [];
      var totalArr = [];

      function doCombinationCallback(arr, curr_index) {
        for (var val of arr[curr_index]) {
          tmp[curr_index] = val;
          if (curr_index < count) {
            doCombinationCallback(arr, curr_index + 1);
          } else {
            totalArr.push(tmp);
          }
          var oldTmp = tmp;
          tmp = [];
          for (var index of oldTmp) {
            tmp.push(index);
          }
        }
        return totalArr;
      }
      return doCombinationCallback(arr, 0);
    },

    getattrprice() {
      var arr = [];
      this.attrubutetable.forEach(f => {
        var b = [];
        if (f.index > -1) {
          for (var i = 0; i < f.attrindexlist.length; i++) {
            if (f.attrindexlist[i] == 1) {
              b.push(this.attrlist[f.index].type_attr[i]);
            }
          }
        }
        if (b.length > 0) {
          arr.push(b);
        }
      });
      return arr.length == 0 ? [] : this.doCombination(arr);
    },

  }
};
</script>
<style scoped="scoped">
.activeattr {
  border: 1px solid rgb(64, 158, 255);
  color: rgb(64, 158, 255);
}

.avatar {
  width: 100%;
  height: 100%;
}

.el-upload {
  width: 100px !important;
  height: 100px !important;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  border-radius: 6px;
}

.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
